package io.tec.cloud.algorithm.c03_v20220607;

import java.util.Objects;

public class DoubleNode<T> {

    T data;
    DoubleNode<T> last;
    DoubleNode<T> next;

    public DoubleNode(T data) {
        this.data = data;
    }

    public DoubleNode() {
    }

    public static DoubleNode copy(DoubleNode head) {
        if (head == null) {
            return null;
        }
        DoubleNode newHead = new DoubleNode(head.data);
        ;
        DoubleNode pre = null;
        DoubleNode curr = newHead;
        DoubleNode cursor = head;
        cursor = cursor.next;
        while (cursor != null) {
            DoubleNode node = new DoubleNode(cursor.data);
            curr.next = node;
            curr.last = pre;
            pre = curr;
            curr = curr.next;
            cursor = cursor.next;
        }
        return newHead;
    }

    public static void print(DoubleNode head) {
        DoubleNode curr = head;
        while (curr != null) {
            System.out.print(curr.data + "-->");
            curr = curr.next;
        }
        System.out.println("Null");
    }

    /**
     * 递归equals，会内存溢出
     *
     * Exception in thread "main" java.lang.StackOverflowError
     * 	at java.util.Objects.equals(Objects.java:59)
     *
     * @param o
     * @return
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DoubleNode<?> that = (DoubleNode<?>) o;
//        return Objects.equals(data, that.data) && Objects.equals(last, that.last);
        return Objects.equals(data, that.data) && Objects.equals(next, that.next);
//        return Objects.equals(data, that.data) && Objects.equals(last, that.last) && Objects.equals(data, that.data) && Objects.equals(next, that.next);
    }

    @Override
    public int hashCode() {
        return Objects.hash(data, last, next);
    }
}